/**
 * Description:
 * User: Vijay <1937832819@qq.com>
 * Date: 2020/08/21
 * Time: 18:39
 */

package api

import (
	"blogApi/controllers"
	"blogApi/models"
	"encoding/json"
	"github.com/astaxie/beego/orm"
	"github.com/dgrijalva/jwt-go"
	"time"
)

type AdminController struct {
	controllers.BaseController
}

type InputData struct {
	Username string
	Password string
}

//用户登录
func (self *AdminController) Login() {
	if self.Ctx.Input.IsPost() == false {
		self.ResJson(1, "操作失败", "请求方式失败", nil)
	}
	var Input InputData
	// 获取字符串形式的参数，用于ajax
	username := self.GetString("username")
	password := self.GetString("password")
	if username == "" && password == "" {
		// 获取 axios 传递的参数
		data := self.Ctx.Input.RequestBody
		err := json.Unmarshal(data, &Input)
		if err != nil {
			self.ResJson(1, "存入失败", err.Error(), nil)
		}
		username = Input.Username
		password = Input.Password
	}
	if username == "" || password == "" {
		self.ResJson(1, "获取失败", "账号或密码为空", nil)
	}
	var admin models.Admin
	o := orm.NewOrm()
	qs := o.QueryTable(admin.TableName()) // 获取 QuerySeter 对象
	cond := orm.NewCondition()
	cond1 := cond.And("account", username).Or("tel", username).Or("email", username)
	cond2 := cond.And("status", 1).And("deleted_at__isnull", true)
	conds := cond.AndCond(cond1).AndCond(cond2)
	qs = qs.SetCond(conds)
	err := qs.One(&admin)
	if err == orm.ErrMultiRows { // 多条的时候报错
		self.ResJson(1, "获取失败", "返回的多行不是一个", nil)
	}
	if err == orm.ErrNoRows { // 没有找到记录
		self.ResJson(1, "获取失败", "账号错误", nil)
	}
	//验证密码
	password = "123456"
	if password != "123456" {
		self.ResJson(1, "获取失败", "密码错误", nil)
	}
	// 带权限创建令牌
	claims := make(jwt.MapClaims)
	claims["account"] = admin.Account
	claims["username"] = admin.Username
	claims["tel"] = admin.Tel
	claims["email"] = admin.Email
	claims["exp"] = time.Now().Add(time.Hour * 2).Unix() //2小时有效期，过期需要重新登录获取token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// 使用自定义字符串加密 and get the complete encoded token as a string
	tokenString, err := token.SignedString([]byte("mykey"))
	if err != nil {
		return
	}
	jsonData := make(map[string]interface{}, 4)
	jsonData["token"] = tokenString
	jsonData["id"] = admin.Id
	jsonData["account"] = admin.Account
	jsonData["username"] = admin.Username
	jsonData["tel"] = admin.Tel
	jsonData["email"] = admin.Email
	self.ResJson(0, "获取成功", jsonData, nil)
}

func (self *AdminController) logout() {

}
